import cv2
import numpy as np
#定义窗口名称
winName='The Circles'
#定义滑动条回调函数，此处pass用作占位语句保持程序结构的完整性
def nothing(x):
    pass
def limit_min(x,min,max):
    if x<min:
        x = min
    elif x>max:
        x = max
    return x
img_original=cv2.imread('DepthImg_21.png')
#转灰度图
GrayImg = cv2.cvtColor(img_original,cv2.COLOR_BGRA2GRAY)
#新建窗口
cv2.namedWindow(winName, cv2.WINDOW_NORMAL)


cv2.imshow(winName,img_original)

#新建6个滑动条，表示颜色范围的上下边界，这里滑动条的初始化位置即为黄色的颜色范围
cv2.createTrackbar('min_dist',winName,0,255,nothing)
cv2.createTrackbar('param_1',winName,0,255,nothing)
cv2.createTrackbar('param_2',winName,0,255,nothing)
cv2.createTrackbar('min_radius',winName,255,255,nothing)
cv2.createTrackbar('max_radius',winName,255,255,nothing)
while(1):
    #函数cv2.getTrackbarPos()范围当前滑块对应的值
    Im_show = img_original.copy()
    min_dist=limit_min(cv2.getTrackbarPos('min_dist',winName),1,255)
    
    param_1=limit_min(cv2.getTrackbarPos('param_1',winName),10,255)
    
    param_2=limit_min(cv2.getTrackbarPos('param_2',winName),10,255)
    min_radius=limit_min(cv2.getTrackbarPos('min_radius',winName),10,255)
    max_radius=limit_min(cv2.getTrackbarPos('max_radius',winName),1,255)
    #计算霍夫找圆
    circles = cv2.HoughCircles(GrayImg, cv2.HOUGH_GRADIENT, 1, minDist = min_dist,
                           param1=param_1, param2=param_2, minRadius=min_radius, maxRadius = max_radius)
    #画圆心
    if circles is not None:
            circles = np.uint16(np.around(circles))
            index = circles[0][:,2].argmax()
            max_circle = circles[0][index]
            for i in circles[0,:]:
                cv2.circle(Im_show, (i[0],i[1]),i[2],(0,255,0) ,1)  #画圆
                cv2.circle(Im_show, (i[0], i[1]),2, (0,0,255) ,1)   #点圆心

    cv2.imshow(winName,Im_show)
    if cv2.waitKey(100)==ord('q'):

        break
cv2.destroyAllWindows()
